package com.tmt.jpa.annotation;

import com.tmt.helper.ReflectHelper;
import com.tmt.jpa.jpaservice.impl.DefaultTmtJpaService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 作者：ThreeManTeam
 * 创建时间：2019-05-18 11:51
 */
public class TransientPropertyParser {

    public static <T> void process(T entity, DefaultTmtJpaService jpaService) {
        if (entity == null)
            return;

        try {
            List<Field> fieldList = ReflectHelper.findAllFieldByAnnotation(entity.getClass(), TransientProperty.class, 0);
            fieldList.forEach(y -> {
                //读取TransientProperty注解对象。
                TransientProperty annotation = y.getAnnotation(TransientProperty.class);
                String propPath = annotation.value();
                String[] paths = propPath.split("\\.");

                Object obj = entity;
                for (int i = 0; i < paths.length - 1; i++) {
                    if (StringUtils.isEmpty(paths[i]))
                        break;

                    obj = ReflectHelper.getFieldValue(obj, paths[i]);
                    if (obj == null)
                        break;
                }

                if (obj == null)
                    return;

                String last = paths[paths.length - 1];
                if (StringUtils.isEmpty(last))
                    return;

                try {
                    if (last.endsWith("()")) {
                        Method method = obj.getClass().getMethod(last.replaceAll("\\(\\)", ""), null);
                        obj = method.invoke(obj, null);
                    } else {
                        obj = ReflectHelper.getFieldValue(obj, last);
                    }
                    ReflectHelper.setFieldValue(entity, y.getName(), obj);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static <T> void process(List<T> entities, DefaultTmtJpaService jpaService) {
        if (CollectionUtils.isEmpty(entities))
            return;
        entities.forEach(x -> process(x, jpaService));
    }

}
